<?php

namespace catchAdmin\stock\controller;

use catchAdmin\permissions\model\Users;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\stock\model\MoveMain as MoveMainModel;
use think\Exception;
use think\Response;
use catcher\CatchAuth;
use think\facade\Db;

class MoveMain extends CatchController
{
    
    protected $moveMainModel;
    
    /**
     *
     * @time 2022/06/17 15:39
     * @param MoveMainModel $moveMainModel
     * @return mixed
     */
    public function __construct(MoveMainModel $moveMainModel)
    {
        $this->moveMainModel = $moveMainModel;
    }

    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->moveMainModel->getList($user['tenant_id']));
    }
    
    /**
     *
     * @time 2022/06/17 15:39
     * @param Request $request
     * @return Response
     */
    public function save(Request $request) : Response
    {
        return CatchResponse::success($this->moveMainModel->storeBy($request->post()));
    }

    /**
     * 创建移库申请单
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function create(CatchAuth $auth,Request $request)
    {
        $params = $request->param();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
//        $configs = [];
//        foreach ($params['config_id_two'] as $k=>$v){
//            $configs[] = Db::table('db_warehouse_config')->where('name',$v)->value('config_id');
//        }
        $move = [];

        $mv= [];

//        $mv['move_code'] = 'M'.$user['tenant_id'].date('md').rand(100000,999999);
        //查询当月移库数量
        $this_month_count =  Db::table('db_move_main')->where('tenant_id',$user['tenant_id'])->whereMonth('created_at')->count();
        //移库单证
        $co_code = Db::table('users')->where('id',$user['tenant_id'])->value('co_code');
        if($co_code){
            $head = strtoupper($co_code) . "MV";
        }else{
            $head = "CIWHMV";
        }

        $mv['move_code'] = $head  . date("ym") . str_pad($this_month_count + 1,5,'0',STR_PAD_LEFT);

        $mv['number'] = count($params['info']);

        if($mv['number'] == 0){
            return CatchResponse::fail('移动数量为0，库存移动参数提交错误！');
        }

        $mv['tenant_id'] = $user['tenant_id'];
        $mv['creator_id'] = $user->id;
        $mv['created_at'] = time();
        // 启动事务

        $tempTrayId = [];

        $pick_stock_ids = Db::table('db_pick')->where([
//            ['tenant_id','=',$user['tenant_id']],
            ['deleted_at','=',0],
            ['status','=',0]
        ])->column('stock_id');
        $move_stock_ids = array_column($params['info'],'stock_id');

        if(!empty(array_intersect($pick_stock_ids,$move_stock_ids))){
            return CatchResponse::fail('存在捡货锁定库存，请删除后在操作');
        }

        Db::startTrans();
        try {

            foreach ($params['info'] as $key => $value) {
                $move[$key]['move_id'] = 'm'.$user['tenant_id'].date('md').rand(100000,999999);
                $move[$key]['move_code'] = $mv['move_code'];
                $move[$key]['stock_id'] = $value['stock_id'];//库存ID



                if(empty($value['config_id_two'])){
                    throw new Exception($value['stock_id'] . '没有指定移库位置');
                }

                //1.不允许跨库移动------start
                $warehouseConfigModel = (new \catchAdmin\stock\model\WarehouseConfig());
                $warehouseConfigOldConfig = $warehouseConfigModel->getOneTwoLevelByThreeId($value['config_id'])['level_1_config_id'];
                $warehouseConfigNewConfig = $warehouseConfigModel->getOneTwoLevelByThreeId($value['config_id_two'])['level_1_config_id'];
                if($warehouseConfigOldConfig !== $warehouseConfigNewConfig){
                    $errorKey = (int)$key + 1;
                    throw new Exception(  "第"  . $errorKey . "条数据，存在跨库操作！");
                }
                //1.不允许跨库移动------end


                //2.库位如果没有变化的话------start
                if($value['config_id'] === $value['config_id_two']){
                    $errorKey = (int)$key + 1;
                    throw new Exception(  "第"  . $errorKey . "条数据，库位没有变化！");
                }
                //2.库位如果没有变化的话------end


                $existConfig = Db::table('db_stock')->where('config_id',$value['config_id_two'])->column('tray_id');

                //判断是否整个托盘移走
                //首先拿到这个托盘上，库存记录数，看看有几条
                $oldTrayCounts = Db::table('db_stock')->where('tray_id',$value['tray_id'])->count();
                //看看这次移动，移了几个数量
                $currentTrayCounts = array_count_values(array_column($params['info'],'tray_id'));

                if($oldTrayCounts == $currentTrayCounts[$value['tray_id']]){
                    //说明整个托盘拿走，那么使用原来的托盘ID
                    $newTrayId = $value['tray_id'];
                }elseif(empty($existConfig)){//不是的话，看看目标库位是否有现成托盘
                        //没有的话，生成一个，但是注意，需要把放置放置的托盘保存起来，不是一直生成新的托盘。
                        if(array_key_exists($value['config_id_two'],$tempTrayId)){
                            $newTrayId = $tempTrayId[$value['config_id_two']];
                        }else{
                            //查看目标库位是否有托盘，有就取，没有就生成一个
                            $newTrayId = 't'.date('YmdHis').mt_rand(10000,99999) . $user['tenant_id'];
                            $tempTrayId[$value['config_id_two']] = $newTrayId;
                        }
                }else {//有的话，目前就先放在第一个托盘上
                    $newTrayId = $existConfig[0];
                }

                /* 和上面判断重复，可以直接去掉----目前先不处理 */
                //判断如果托盘上就剩这个一件，托盘也拿走
                $trayBoxSum = Db::table('db_stock')->where('tray_id',$value['tray_id'])->count();
                if(1 == $trayBoxSum){//代表这个托盘上只有一个这个玩意
                    $newTrayId = $value['tray_id'];
                }

                if(!empty($value['tray_id']) && !empty($value['box_id']) && !empty($value['slice_id'])){
                    $move[$key]['tray_id'] = $newTrayId;

                    $move[$key]['box_id'] = $value['box_id'];
                    $move[$key]['slice_id'] = $value['slice_id'];
                    $move[$key]['config_id_one'] = $value['config_id'];
                    $move[$key]['goods_id'] = $value['goods_id'];
                    $move[$key]['goods_name'] = $value['goods_name'];
                    $move[$key]['config_id_two'] = $value['config_id_two'];
                    $move[$key]['creator_id'] = $params['creator_id'];
                    $move[$key]['tenant_id'] = $params['tenant_id'];
                    //$where3['tray_id'] = $value['tray_id'];

                    //Db::table('db_slice')->where($where3)->update(['config_id' => $configs[$key]]);

                }elseif(!empty($value['tray_id']) && !empty($value['box_id']) && empty($value['slice_id'])){
                    $move[$key]['tray_id'] = $newTrayId;

                    $move[$key]['box_id'] = $value['box_id'];
                    $move[$key]['slice_id'] = $value['slice_id'];
                    $move[$key]['config_id_one'] = $value['config_id'];
                    $move[$key]['goods_id'] = $value['goods_id'];
                    $move[$key]['goods_name'] = $value['goods_name'];
                    $move[$key]['config_id_two'] = $value['config_id_two'];
                    $move[$key]['creator_id'] = $params['creator_id'];
                    $move[$key]['tenant_id'] = $params['tenant_id'];



                }elseif(!empty($value['tray_id']) && empty($value['box_id']) && empty($value['slice_id'])){
                    $move[$key]['tray_id'] =$newTrayId;

                    $move[$key]['box_id'] = $value['box_id'];
                    $move[$key]['slice_id'] = $value['slice_id'];
                    $move[$key]['config_id_one'] = $value['config_id'];
                    $move[$key]['goods_id'] = $value['goods_id'];
                    $move[$key]['goods_name'] = $value['goods_name'];
                    $move[$key]['config_id_two'] = $value['config_id_two'];
                    $move[$key]['creator_id'] = $params['creator_id'];
                    $move[$key]['tenant_id'] = $params['tenant_id'];

                    //Db::table('db_stock')->where($where1)->update(['config_id' => $configs[$key]]);
                }
            }

            Db::table('db_move_main')->insert($mv);
            Db::table('db_move')->insertAll($move);

            Db::commit();
            return CatchResponse::success('', '新建成功');
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception("失败\r\n" . $exception->getMessage());
        }
    }
    
    /**
     *
     * @time 2022/06/17 15:39
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function update($id, Request $request) : Response
    {
        return CatchResponse::success($this->moveMainModel->updateBy($id, $request->post()));
    }
    
    /**
     *
     * @time 2022/06/17 15:39
     * @param $id
     * @return Response
     */
    public function delete($id) : Response
    {
        return CatchResponse::success($this->moveMainModel->deleteBy($id));
    }
}